<template>
  <div class="energy-dashboard-fullscreen" ref="dashboardContainer">
    <!-- 全屏切换按钮 -->
    <div class="fullscreen-toggle" @click="toggleFullscreen" :class="{ 'is-fullscreen': isFullscreen }">
      <div class="toggle-icon">
        <span class="icon-expand" v-if="!isFullscreen">⛶</span>
        <span class="icon-compress" v-else>⛷</span>
      </div>
      <div class="toggle-tooltip">{{ isFullscreen ? '退出全屏' : '进入全屏' }}</div>
    </div>

    <!-- 顶部标题区域 -->
    <div class="header-section">
      <div class="main-title">
        <span class="title-text">智慧能源监控大屏</span>
        <div class="title-decoration"></div>
      </div>
      <div class="time-display">
        <div class="current-date">{{ currentDate }}</div>
        <div class="current-time">{{ currentTime }}</div>
      </div>
    </div>

    <!-- 主体内容区域 -->
    <div class="main-content">
      <!-- 左侧区域 -->
      <div class="left-panel">
        <!-- 能耗概览卡片 -->
        <div class="dashboard-card energy-overview">
          <div class="card-header">
            <div class="card-title">能耗概览</div>
            <div class="card-actions">
              <span class="refresh-time">更新于: {{ lastUpdateTime }}</span>
            </div>
          </div>
          <div class="card-content">
            <div class="energy-stats">
              <div class="stat-item">
                <div class="stat-icon">
                  <div class="icon-circle total"></div>
                </div>
                <div class="stat-info">
                  <div class="stat-label">总能耗</div>
                  <div class="stat-value">{{ formatNumber(totalEnergy) }}</div>
                  <div class="stat-unit">kWh</div>
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-icon">
                  <div class="icon-circle avg"></div>
                </div>
                <div class="stat-info">
                  <div class="stat-label">今日能耗</div>
                  <div class="stat-value">{{ formatNumber(todayEnergy) }}</div>
                  <div class="stat-unit">kWh</div>
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-icon">
                  <div class="icon-circle max"></div>
                </div>
                <div class="stat-info">
                  <div class="stat-label">能耗峰值</div>
                  <div class="stat-value">{{ formatNumber(peakEnergy) }}</div>
                  <div class="stat-unit">kWh</div>
                </div>
              </div>
              <div class="stat-item">
                <div class="stat-icon">
                  <div class="icon-circle trend"></div>
                </div>
                <div class="stat-info">
                  <div class="stat-label">同比变化</div>
                  <div class="stat-value" :class="energyTrend >= 0 ? 'positive' : 'negative'">
                    {{ energyTrend >= 0 ? '+' : '' }}{{ energyTrend.toFixed(1) }}%
                  </div>
                  <div class="stat-unit">较上月</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 能耗排名 -->
        <div class="dashboard-card energy-ranking">
          <div class="card-header">
            <div class="card-title">近30天能耗排名</div>
            <div class="dimension-switcher">
              <span class="dimension-label">维度:</span>
              <span class="dimension-value">{{ currentDimension.label }}</span>
            </div>
          </div>
          <div class="card-content">
            <div ref="rankingChart" class="chart-containerQSPM"></div>
          </div>
        </div>
      </div>

      <!-- 中间区域 -->
      <div class="center-panel">
        <!-- 实时能耗监控 -->
        <div class="dashboard-card real-time-monitor">
          <div class="card-header">
            <div class="card-title">实时能耗监控</div>
            <div class="real-time-indicator">
              <div class="pulse-dot"></div>
              <span>实时更新</span>
            </div>
          </div>
          <div class="card-content">
            <div ref="gaugeChart" class="chart-container"></div>
            <div class="gauge-stats">
              <div class="gauge-stat">
                <div class="gauge-label">当前负荷</div>
                <div class="gauge-value">{{ currentLoad }}%</div>
              </div>
              <div class="gauge-stat">
                <div class="gauge-label">运行状态</div>
                <div class="gauge-value status-normal">正常</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 能耗趋势 -->
        <div class="dashboard-card energy-trend">
          <div class="card-header">
            <div class="card-title">能耗趋势分析</div>
            <div class="trend-period">{{ trendPeriod }}</div>
          </div>
          <div class="card-content">
            <div ref="trendChart" class="chart-containerQSPM"></div>
          </div>
        </div>
      </div>

      <!-- 右侧区域 -->
      <div class="right-panel">
        <!-- 能耗分布 -->
        <div class="dashboard-card energy-distribution">
          <div class="card-header">
            <div class="card-title">能耗分布</div>
            <div class="distribution-type">{{ distributionType }}</div>
          </div>
          <div class="card-content">
            <div ref="distributionChart" class="chart-container"></div>
          </div>
        </div>

        <!-- 异常预警 -->
        <div class="dashboard-card alert-panel">
          <div class="card-header">
            <div class="card-title">异常预警</div>
            <div class="alert-count" :class="alertCount > 0 ? 'has-alerts' : ''">
              {{ alertCount }} 条预警
            </div>
          </div>
          <div class="card-content">
            <div class="alert-list">
              <div v-for="(alert, index) in alerts" :key="index" class="alert-item">
                <div class="alert-icon" :class="alert.level">
                  <i class="icon-warning">!</i>
                </div>
                <div class="alert-content">
                  <div class="alert-title">{{ alert.title }}</div>
                  <div class="alert-time">{{ alert.time }}</div>
                </div>
              </div>
              <div v-if="alerts.length === 0" class="no-alerts">
                <div class="no-alerts-icon">✓</div>
                <div class="no-alerts-text">系统运行正常</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部信息栏 -->
    <div class="footer-section">
      <div class="footer-info">
        <span class="info-item">数据更新时间: {{ lastUpdateTime }}</span>
        <span class="info-item">当前维度: {{ currentDimension.label }}</span>
        <span class="info-item">自动刷新: 30秒</span>
      </div>
      <div class="system-status">
        <span class="status-item">系统状态: <span class="status-normal">正常</span></span>
        <span class="status-item">连接状态: <span class="status-normal">已连接</span></span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue'
import { request } from '@/utils/request'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 全屏状态和容器引用
const isFullscreen = ref(false)
const dashboardContainer = ref(null)

// 能耗数据
const currentDate = ref('')
const currentTime = ref('')
const lastUpdateTime = ref('')
const totalEnergy = ref(12560) //总能耗
const todayEnergy = ref(385)//今日能耗
const peakEnergy = ref(890)//能耗峰值
const energyTrend = ref(2.5)//同比变化


// 维度切换
const dimensions = [
  { value: 'device', label: '设备' },
  { value: 'workshop', label: '车间' },
  { value: 'productionLine', label: '产线' },
  { value: 'substance', label: '物质' }
]
const currentDimensionIndex = ref(0)
const currentDimension = computed(() => dimensions[currentDimensionIndex.value])

// 预警数据
const alerts = ref([
  { level: 'high', title: '设备A能耗异常升高', time: '10:25:30' },
  { level: 'medium', title: '车间B用电量超阈值', time: '09:45:12' }
])
const alertCount = computed(() => alerts.value.length)

// 图表引用
const rankingChart = ref(null)
const gaugeChart = ref(null)
const trendChart = ref(null)
const distributionChart = ref(null)

// 图表实例
let rankingChartInstance = null
let gaugeChartInstance = null
let trendChartInstance = null
let distributionChartInstance = null

// 定时器
let timeInterval = null
let dataRefreshInterval = null
let dimensionSwitchInterval = null

// 计算属性
const trendPeriod = computed(() => {
  const now = new Date()
  const month = now.getMonth() + 1
  return `${month}月能耗趋势`
})

const distributionType = computed(() => {
  return `${currentDimension.value.label}分布`
})

// 全屏切换功能 - 只针对当前组件容器
const toggleFullscreen = async () => {
  // 确保组件已经挂载
  await nextTick()
  
  if (!dashboardContainer.value) {
    console.error('Dashboard container not found')
    return
  }
  
  if (!isFullscreen.value) {
    // 进入全屏
    enterFullscreen()
  } else {
    // 退出全屏
    exitFullscreen()
  }
}

// 进入全屏
const enterFullscreen = () => {
  const element = dashboardContainer.value
  
  if (!element) {
    console.error('No element found for fullscreen')
    return
  }
  
  if (element.requestFullscreen) {
    element.requestFullscreen().catch(err => {
      console.error('Error attempting to enable fullscreen:', err)
      // 如果全屏API失败，使用备用方案
      fallbackFullscreen()
    })
  } else if (element.mozRequestFullScreen) { /* Firefox */
    element.mozRequestFullScreen().catch(err => {
      console.error('Error attempting to enable fullscreen:', err)
      fallbackFullscreen()
    })
  } else if (element.webkitRequestFullscreen) { /* Chrome, Safari and Opera */
    element.webkitRequestFullscreen().catch(err => {
      console.error('Error attempting to enable fullscreen:', err)
      fallbackFullscreen()
    })
  } else if (element.msRequestFullscreen) { /* IE/Edge */
    element.msRequestFullscreen().catch(err => {
      console.error('Error attempting to enable fullscreen:', err)
      fallbackFullscreen()
    })
  } else {
    // 如果不支持全屏API，使用CSS模拟全屏
    fallbackFullscreen()
  }
}

// 退出全屏
const exitFullscreen = () => {
  if (document.exitFullscreen) {
    document.exitFullscreen().catch(err => {
      console.error('Error attempting to exit fullscreen:', err)
      fallbackExitFullscreen()
    })
  } else if (document.mozCancelFullScreen) { /* Firefox */
    document.mozCancelFullScreen().catch(err => {
      console.error('Error attempting to exit fullscreen:', err)
      fallbackExitFullscreen()
    })
  } else if (document.webkitExitFullscreen) { /* Chrome, Safari and Opera */
    document.webkitExitFullscreen().catch(err => {
      console.error('Error attempting to exit fullscreen:', err)
      fallbackExitFullscreen()
    })
  } else if (document.msExitFullscreen) { /* IE/Edge */
    document.msExitFullscreen().catch(err => {
      console.error('Error attempting to exit fullscreen:', err)
      fallbackExitFullscreen()
    })
  } else {
    // 如果是CSS模拟全屏，退出
    fallbackExitFullscreen()
  }
}

// CSS模拟全屏（备用方案）
const fallbackFullscreen = () => {
  if (!dashboardContainer.value) return
  
  const element = dashboardContainer.value
  element.classList.add('fallback-fullscreen')
  isFullscreen.value = true
  
  // 重新调整图表大小
  setTimeout(() => {
    if (rankingChartInstance) rankingChartInstance.resize()
    if (gaugeChartInstance) gaugeChartInstance.resize()
    if (trendChartInstance) trendChartInstance.resize()
    if (distributionChartInstance) distributionChartInstance.resize()
  }, 100)
}

// 退出CSS模拟全屏
const fallbackExitFullscreen = () => {
  if (!dashboardContainer.value) return
  
  const element = dashboardContainer.value
  element.classList.remove('fallback-fullscreen')
  isFullscreen.value = false
  
  // 重新调整图表大小
  setTimeout(() => {
    if (rankingChartInstance) rankingChartInstance.resize()
    if (gaugeChartInstance) gaugeChartInstance.resize()
    if (trendChartInstance) trendChartInstance.resize()
    if (distributionChartInstance) distributionChartInstance.resize()
  }, 100)
}

// 监听全屏状态变化
const handleFullscreenChange = () => {
  const fullscreenElement = document.fullscreenElement || 
                           document.mozFullScreenElement ||
                           document.webkitFullscreenElement ||
                           document.msFullscreenElement
  
  isFullscreen.value = !!fullscreenElement
  
  // 如果全屏元素是我们的容器，调整图表大小
  if (fullscreenElement === dashboardContainer.value) {
    setTimeout(() => {
      if (rankingChartInstance) rankingChartInstance.resize()
      if (gaugeChartInstance) gaugeChartInstance.resize()
      if (trendChartInstance) trendChartInstance.resize()
      if (distributionChartInstance) distributionChartInstance.resize()
    }, 100)
  }
}

// 键盘事件监听（ESC退出全屏）
const handleKeydown = (event) => {
  if (event.key === 'Escape' && isFullscreen.value) {
    exitFullscreen()
  }
}

// 更新时间
const updateDateTime = () => {
  const now = new Date()
  currentDate.value = now.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    weekday: 'long'
  })
  currentTime.value = now.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
  lastUpdateTime.value = now.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
 const  currentLoad = computed(()=>{
      return (todayEnergy.value/1000 *100).toFixed(1) //当前负荷率 ：今日能耗/额定功率 *100
     }) 
// 初始化图表
const initCharts = () => {

  nextTick(() => {

    //获取能耗信息数据
    //  totalEnergy = ref(12560) //总能耗
    //  todayEnergy = ref(385)//今日能耗
    //  peakEnergy = ref(890)//能耗峰值
    //  energyTrend = ref(2.5)//同比变化
    

    // 初始化排名图表
    if (rankingChart.value) {
      rankingChartInstance = echarts.init(rankingChart.value)
      renderRankingChart()
    }
    
    // 初始化仪表盘图表
    if (gaugeChart.value) {
      gaugeChartInstance = echarts.init(gaugeChart.value)
      renderGaugeChart()
    }
    
    // 初始化趋势图表
    if (trendChart.value) {
      trendChartInstance = echarts.init(trendChart.value)
      renderTrendChart()
    }
    
    // 初始化分布图表
    if (distributionChart.value) {
      distributionChartInstance = echarts.init(distributionChart.value)
      renderDistributionChart()
    }
  })
}

// 渲染排名图表
const renderRankingChart = async () => {
  if (!rankingChartInstance) return
  
  // 根据当前维度生成数据
  const data =  await generateRankingData(currentDimension.value.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      borderColor: 'rgba(25, 163, 223, 0.8)',
      textStyle: {
        color: '#fff'
      },
      formatter: function(params) {
        return `${params[0].name}<br/>能耗: ${params[0].value} kWh`
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.7)'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      }
    },
    yAxis: {
      type: 'category',
      data: data.categories,
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.7)'
      }
    },
    series: [
      {
        name: '能耗',
        type: 'bar',
        data: data.data,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#19a3df' },
            { offset: 1, color: '#7ed6ff' }
          ]),
          borderRadius: [0, 4, 4, 0]
        },
        emphasis: {
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
              { offset: 0, color: '#ff8c37' },
              { offset: 1, color: '#ffc107' }
            ])
          }
        },
        label: {
          show: true,
          position: 'inside',
          color: '#fff',
          formatter: '{c} kWh'
        }
      }
    ]
  }
  
  rankingChartInstance.setOption(option)
}

// 生成排名数据
const  generateRankingData = async (dimension) => {

  const backendData = await  request.post('/Energy/EC/KANBAN_PM')
  
  //   const backendData = {
  //   "device": [
  //     { "name": "设备A", "energyConsumption": 21 },
  //     { "name": "设备B", "energyConsumption": 40 },
  //     { "name": "设备C", "energyConsumption": 55 },
  //     { "name": "设备D", "energyConsumption": 61 }
  //   ],
  //   "workshop": [
  //     { "name": "车间A", "energyConsumption": 21 },
  //     { "name": "车间B", "energyConsumption": 40 },
  //     { "name": "车间C", "energyConsumption": 116 }
  //   ],
  //   "productionLine": [
  //     { "name": "产线B", "energyConsumption": 21 },
  //     { "name": "产线C", "energyConsumption": 40 },
  //     { "name": "产线D", "energyConsumption": 55 },
  //     { "name": "产线E", "energyConsumption": 61 }
  //   ],
  //   "substance": [
  //     { "name": "电", "energyConsumption": 40 },
  //     { "name": "燃气", "energyConsumption": 61 },
  //     { "name": "水", "energyConsumption": 21 },
  //     { "name": "蒸汽", "energyConsumption": 55 }
  //   ]
  // }
  // 获取对应维度的数据
  const dimensionData = backendData[dimension] || backendData.device
  // 按能耗从高到低排序
  const sortedData = dimensionData.sort((a, b) => b.energyConsumption - a.energyConsumption)
  
  // 提取分类和数据
  const categories = sortedData.map(item => item.name)
  const data = sortedData.map(item => item.energyConsumption)
  
  return {
    categories,
    data
  }
}

// 渲染仪表盘图表
const renderGaugeChart = () => {
  if (!gaugeChartInstance) return
  
  const option = {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 10,
        radius: '90%',
        center: ['50%', '60%'],
        axisLine: {
          lineStyle: {
            width: 10,
            color: [
              [0.3, '#19a3df'],
              [0.7, '#37c6c0'],
              [1, '#ff6b6b']
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '12%',
          width: 10,
          offsetCenter: [0, '-60%'],
          itemStyle: {
            color: 'auto'
          }
        },
        axisTick: {
          length: 8,
          lineStyle: {
            color: 'auto',
            width: 2
          }
        },
        splitLine: {
          length: 15,
          lineStyle: {
            color: 'auto',
            width: 3
          }
        },
        axisLabel: {
          color: '#fff',
          fontSize: 12,
          distance: -30,
          formatter: function(value) {
            if (value === 0) return '低'
            if (value === 50) return '中'
            if (value === 100) return '高'
            return ''
          }
        },
        title: {
          offsetCenter: [0, '20%'],
          fontSize: 16,
          color: '#fff'
        },
        detail: {
          fontSize: 30,
          offsetCenter: [0, '0%'],
          valueAnimation: true,
          formatter: '{value}%',
          color: 'auto'
        },
        data: [
          {
            value: currentLoad.value,
            name: '当前负荷'
          }
        ]
      }
    ]
  }
  
  gaugeChartInstance.setOption(option)
}

// 渲染趋势图表
const renderTrendChart = () => {
  if (!trendChartInstance) return
  
  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      borderColor: 'rgba(25, 163, 223, 0.8)',
      textStyle: {
        color: '#fff'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1日', '5日', '10日', '15日', '20日', '25日', '30日'],
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.7)'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.3)'
        }
      },
      axisLabel: {
        color: 'rgba(255, 255, 255, 0.7)',
        formatter: '{value} kWh'
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.1)'
        }
      }
    },
    series: [
      {
        name: '能耗',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          width: 3,
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#19a3df' },
            { offset: 1, color: '#37c6c0' }
          ])
        },
        itemStyle: {
          color: '#ffc107'
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(25, 163, 223, 0.5)' },
            { offset: 1, color: 'rgba(25, 163, 223, 0.1)' }
          ])
        },
        data: [320, 302, 301, 334, 390, 330, 320]
      }
    ]
  }
  
  trendChartInstance.setOption(option)
}

// 渲染分布图表
const renderDistributionChart = async ()  => {
  if (!distributionChartInstance) return
  
  // 根据当前维度生成数据
  const data = await generateDistributionData(currentDimension.value.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(0, 0, 0, 0.7)',
      borderColor: 'rgba(25, 163, 223, 0.8)',
      textStyle: {
        color: '#fff'
      }
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      textStyle: {
        color: 'rgba(255, 255, 255, 0.7)'
      }
    },
    series: [
      {
        name: '能耗分布',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['40%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#0a1a35',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 18,
            fontWeight: 'bold',
            color: '#fff'
          }
        },
        labelLine: {
          show: false
        },
        data: data
      }
    ]
  }
  
  distributionChartInstance.setOption(option)
}

// 生成分布数据
const generateDistributionData = async (dimension) => {
  const backendData = await  request.post('/Energy/EC/KANBAN_PM')
  const dataMap = {
    device: [
      { value: 1200, name: '设备A', itemStyle: { color: '#19a3df' } },
      { value: 980, name: '设备B', itemStyle: { color: '#37c6c0' } },
      { value: 760, name: '设备C', itemStyle: { color: '#ff8c37' } },
      { value: 620, name: '设备D', itemStyle: { color: '#ffc107' } },
      { value: 480, name: '设备E', itemStyle: { color: '#ff6b6b' } }
    ],
    workshop: [
      { value: 3200, name: '车间A', itemStyle: { color: '#19a3df' } },
      { value: 2850, name: '车间B', itemStyle: { color: '#37c6c0' } },
      { value: 2100, name: '车间C', itemStyle: { color: '#ff8c37' } },
      { value: 1800, name: '车间D', itemStyle: { color: '#ffc107' } }
    ],
    productionLine: [
      { value: 1800, name: '产线A', itemStyle: { color: '#19a3df' } },
      { value: 1650, name: '产线B', itemStyle: { color: '#37c6c0' } },
      { value: 1420, name: '产线C', itemStyle: { color: '#ff8c37' } },
      { value: 1100, name: '产线D', itemStyle: { color: '#ffc107' } },
      { value: 950, name: '产线E', itemStyle: { color: '#ff6b6b' } }
    ],
    substance: [
      { value: 8560, name: '电力', itemStyle: { color: '#19a3df' } },
      { value: 2850, name: '燃气', itemStyle: { color: '#37c6c0' } },
      { value: 850, name: '水', itemStyle: { color: '#ff8c37' } },
      { value: 300, name: '蒸汽', itemStyle: { color: '#ffc107' } }
    ]
  }
  
  // 获取对应维度的数据
  const dimensionData = backendData[dimension] || backendData.device
  
  // 定义颜色数组
  const colors = ['#19a3df', '#37c6c0', '#ff8c37', '#ffc107', '#ff6b6b']
  
  // 转换为饼图需要的数据格式
  return dimensionData.map((item, index) => ({
    value: item.energyConsumption,
    name: item.name,
    itemStyle: { 
      color: colors[index % colors.length] 
    }
  }))
}

// 切换维度
const switchDimension = () => {
  currentDimensionIndex.value = (currentDimensionIndex.value + 1) % dimensions.length
  renderRankingChart()
  renderDistributionChart()
}

// 格式化数字
const formatNumber = (value) => {
  if (value === null || value === undefined) return '0'
  return Number(value).toLocaleString()
}

// 从后端加载数据
const loadDashboardData = async () => {
  try {
    // 构建查询参数
    const params = {
      dimension: currentDimension.value.value,
      // 其他参数...
    }
    
    // 调用后端API - 这里需要根据实际接口调整
    // const response = await request.post('/Energy/Dashboard/Fullscreen', params)
    
    // 模拟API响应延迟
    // await new Promise(resolve => setTimeout(resolve, 500))
    
    // 使用示例数据（实际使用时请替换为API返回的数据）
    // 这里可以更新所有图表数据
    
  } catch (error) {
    console.error('加载大屏数据失败:', error)
    // 如果API调用失败，使用示例数据
  }
}

// 页面加载时初始化
onMounted(() => {
  // 确保DOM已经渲染
  nextTick(() => {
    // 初始化时间
    updateDateTime()
    
    // 初始化图表
    initCharts()
  })
  
  // 设置时间更新定时器
  timeInterval = setInterval(updateDateTime, 1000)
  
  // 设置数据刷新定时器（30秒）
  dataRefreshInterval = setInterval(() => {
    loadDashboardData()
  }, 30000)
  
  // 设置维度切换定时器（30秒）
  dimensionSwitchInterval = setInterval(switchDimension, 30000)
  
  // 添加全屏变化事件监听
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.addEventListener('mozfullscreenchange', handleFullscreenChange)
  document.addEventListener('MSFullscreenChange', handleFullscreenChange)
  
  // 添加键盘事件监听
  document.addEventListener('keydown', handleKeydown)
})

// 处理窗口大小变化
const handleResize = () => {
  if (rankingChartInstance) rankingChartInstance.resize()
  if (gaugeChartInstance) gaugeChartInstance.resize()
  if (trendChartInstance) trendChartInstance.resize()
  if (distributionChartInstance) distributionChartInstance.resize()
}

// 组件卸载时清理
onUnmounted(() => {
  if (timeInterval) clearInterval(timeInterval)
  if (dataRefreshInterval) clearInterval(dataRefreshInterval)
  if (dimensionSwitchInterval) clearInterval(dimensionSwitchInterval)
  
  if (rankingChartInstance) rankingChartInstance.dispose()
  if (gaugeChartInstance) gaugeChartInstance.dispose()
  if (trendChartInstance) trendChartInstance.dispose()
  if (distributionChartInstance) distributionChartInstance.dispose()
  
  // 移除全屏事件监听
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
  document.removeEventListener('mozfullscreenchange', handleFullscreenChange)
  document.removeEventListener('MSFullscreenChange', handleFullscreenChange)
  
  // 移除键盘事件监听
  document.removeEventListener('keydown', handleKeydown)
  
  // 移除窗口大小变化监听
  window.removeEventListener('resize', handleResize)
  
  // 如果还在全屏状态，退出全屏
  if (isFullscreen.value) {
    exitFullscreen()
  }
})
</script>

<style scoped>
.energy-dashboard-fullscreen {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #0a1a35 0%, #152642 50%, #1c2e4a 100%); 
  color: #fff;
  overflow: hidden;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  position: relative;
}

/* 全屏切换按钮样式 */
.fullscreen-toggle {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 36px;
  height: 36px;
  background: rgba(25, 163, 223, 0.1);
  border: 1px solid rgba(25, 163, 223, 0.3);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1000;
  opacity: 0.5;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
}

.fullscreen-toggle:hover {
  opacity: 1;
  background: rgba(25, 163, 223, 0.2);
  border-color: rgba(25, 163, 223, 0.6);
  transform: scale(1.05);
}

.toggle-icon {
  color: #19a3df;
  font-size: 16px;
  font-weight: bold;
}

.toggle-tooltip {
  position: absolute;
  top: 100%;
  right: 0;
  margin-top: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 6px 10px;
  border-radius: 4px;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  transform: translateY(-10px);
  transition: all 0.3s ease;
  pointer-events: none;
  z-index: 1001;
}

.fullscreen-toggle:hover .toggle-tooltip {
  opacity: 1;
  transform: translateY(0);
}

/* 全屏状态下的按钮样式 */
.fullscreen-toggle.is-fullscreen {
  background: rgba(255, 107, 107, 0.1);
  border-color: rgba(255, 107, 107, 0.3);
}

.fullscreen-toggle.is-fullscreen .toggle-icon {
  color: #ff6b6b;
}

/* CSS模拟全屏样式 */
.energy-dashboard-fullscreen.fallback-fullscreen {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100vw !important;
  height: 100vh !important;
  z-index: 9999 !important;
  background: linear-gradient(135deg, #0a1a35 0%, #152642 50%, #1c2e4a 100%) !important; 
}

/* 响应式调整 */
@media (max-width: 1600px) {
  .fullscreen-toggle {
    top: 15px;
    right: 15px;
    width: 32px;
    height: 32px;
  }
  
  .toggle-icon {
    font-size: 14px;
  }
}

.energy-dashboard-fullscreen {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #0a1a35 0%, #152642 50%, #1c2e4a 100%);
  color: #fff;
  overflow: hidden;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  position: relative;
}

/* 顶部标题区域 */
.header-section {
  height: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  background: rgba(10, 26, 53, 0.8);
  border-bottom: 1px solid rgba(25, 163, 223, 0.3);
  position: relative;
  z-index: 10;
}

.main-title {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.title-text {
  font-size: 32px;
  font-weight: bold;
  background: linear-gradient(90deg, #19a3df, #37c6c0);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 0 10px rgba(25, 163, 223, 0.5);
}

.title-decoration {
  width: 100px;
  height: 3px;
  background: linear-gradient(90deg, transparent, #19a3df, transparent);
  margin-top: 5px;
}

.time-display {
  text-align: right;
}

.current-date {
  font-size: 18px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 5px;
}

.current-time {
  font-size: 24px;
  font-weight: bold;
  color: #19a3df;
  text-shadow: 0 0 10px rgba(25, 163, 223, 0.5);
}

/* 主体内容区域 */
.main-content {
  height: calc(100vh - 140px);
  display: flex;
  padding: 20px;
  gap: 20px;
}

.left-panel, .right-panel {
  width: 25%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.center-panel {
  width: 50%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 卡片样式 */
.dashboard-card {
  background: rgba(16, 33, 60, 0.7);
  border: 1px solid rgba(25, 163, 223, 0.2);
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  overflow: hidden;
  position: relative;
}

.dashboard-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(90deg, #19a3df, #37c6c0);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.card-title {
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  position: relative;
  padding-left: 12px;
}

.card-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background: #19a3df;
  border-radius: 2px;
}

.card-actions {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.card-content {
  padding: 15px;
  height: calc(100% - 60px);
}

/* 能耗概览样式 */
.energy-overview {
  height: 340px;
}

.energy-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  height: 100%;
}

.stat-item {
  display: flex;
  align-items: center;
  background: rgba(25, 163, 223, 0.1);
  border-radius: 6px;
  padding: 15px;
  border: 1px solid rgba(25, 163, 223, 0.2);
}

.stat-icon {
  margin-right: 15px;
}

.icon-circle {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  color: #fff;
}

.icon-circle.total {
  background: linear-gradient(135deg, #19a3df, #37c6c0);
}

.icon-circle.avg {
  background: linear-gradient(135deg, #ff8c37, #ffc107);
}

.icon-circle.max {
  background: linear-gradient(135deg, #ff6b6b, #ff8c37);
}

.icon-circle.trend {
  background: linear-gradient(135deg, #37c6c0, #19a3df);
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 5px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 2px;
}

.stat-value.positive {
  color: #ff6b6b;
}

.stat-value.negative {
  color: #37c6c0;
}

.stat-unit {
  font-size: 10px;
  color: rgba(255, 255, 255, 0.5);
}

/* 图表容器 */
.chart-container {
  width: 100%;
  height: 80%;
}
/* 图表趋势容器 */
.chart-containerQSPM {
  width: 100%;
  height: 100%;
}

.energy-ranking {
  height: calc(100% - 240px);
}

.real-time-monitor {
  height: 300px;
}

.energy-trend {
  height: calc(100% - 320px);
}

.energy-distribution {
  height: 300px;
}

.alert-panel {
  height: calc(100% - 320px);
}

/* 实时监控样式 */
.real-time-indicator {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #37c6c0;
}

.pulse-dot {
  width: 8px;
  height: 8px;
  background: #37c6c0;
  border-radius: 50%;
  margin-right: 5px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(55, 198, 192, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(55, 198, 192, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(55, 198, 192, 0);
  }
}

.gauge-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.gauge-stat {
  text-align: center;
}

.gauge-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 5px;
}

.gauge-value {
  font-size: 18px;
  font-weight: bold;
}

.status-normal {
  color: #37c6c0;
}

/* 预警面板样式 */
.alert-list {
  height: 100%;
  overflow-y: auto;
}

.alert-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  background: rgba(255, 107, 107, 0.1);
  border-radius: 6px;
  border-left: 3px solid #ff6b6b;
}

.alert-item:nth-child(2) {
  background: rgba(255, 140, 55, 0.1);
  border-left-color: #ff8c37;
}

.alert-icon {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 14px;
}

.alert-icon.high {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
}

.alert-icon.medium {
  background: rgba(255, 140, 55, 0.2);
  color: #ff8c37;
}

.alert-content {
  flex: 1;
}

.alert-title {
  font-size: 14px;
  margin-bottom: 3px;
}

.alert-time {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
}

.no-alerts {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: rgba(255, 255, 255, 0.5);
}

.no-alerts-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(55, 198, 192, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #37c6c0;
  margin-bottom: 10px;
}

/* 维度切换器 */
.dimension-switcher {
  display: flex;
  align-items: center;
  font-size: 12px;
}

.dimension-label {
  color: rgba(255, 255, 255, 0.6);
  margin-right: 5px;
}

.dimension-value {
  color: #19a3df;
  font-weight: bold;
}

/* 趋势周期 */
.trend-period {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

/* 分布类型 */
.distribution-type {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

/* 预警计数 */
.alert-count {
  font-size: 12px;
  padding: 3px 8px;
  border-radius: 10px;
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
}

.alert-count.has-alerts {
  animation: blink 2s infinite;
}

@keyframes blink {
  0%, 50% {
    opacity: 1;
  }
  51%, 100% {
    opacity: 0.5;
  }
}

/* 底部信息栏 */
.footer-section {
  height: 60px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  background: rgba(10, 26, 53, 0.8);
  border-top: 1px solid rgba(25, 163, 223, 0.3);
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.footer-info, .system-status {
  display: flex;
  gap: 20px;
}

/* 响应式调整 */
@media (max-width: 1600px) {
  .main-content {
    padding: 15px;
  }
  
  .left-panel, .right-panel {
    width: 28%;
  }
  
  .center-panel {
    width: 44%;
  }
}
</style>